{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np # 导入 numpy 库\n",
    "import torch # 导入 torch 库\n",
    "import torch.nn as nn # 导入 torch.nn 库\n",
    "import torch.optim as optim # 导入优化器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "d_k = 64 # K(=Q) 维度\n",
    "d_v = 64 # V 维度\n",
    "# 定义缩放点积注意力类\n",
    "class ScaledDotProductAttention(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(ScaledDotProductAttention, self).__init__()        \n",
    "    def forward(self, Q, K, V, attn_mask):\n",
    "        #------------------------- 维度信息 --------------------------------        \n",
    "        # Q K V [batch_size, n_heads, len_q/k/v, dim_q=k/v] (dim_q=dim_k)\n",
    "        # attn_mask [batch_size, n_heads, len_q, len_k]\n",
    "        #----------------------------------------------------------------\n",
    "        # 计算注意力分数（原始权重）[batch_size，n_heads，len_q，len_k]\n",
    "        scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) \n",
    "        #------------------------- 维度信息 --------------------------------        \n",
    "        # scores [batch_size, n_heads, len_q, len_k]\n",
    "        #-----------------------------------------------------------------        \n",
    "        # 使用注意力掩码，将 attn_mask 中值为 1 的位置的权重替换为极小值\n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # attn_mask [batch_size, n_heads, len_q, len_k], 形状和 scores 相同\n",
    "        #-----------------------------------------------------------------    \n",
    "        attn_mask = attn_mask.to(torch.bool)\n",
    "        scores.masked_fill_(attn_mask, -1e9) \n",
    "        # 对注意力分数进行 softmax 归一化\n",
    "        weights = nn.Softmax(dim=-1)(scores) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # weights [batch_size, n_heads, len_q, len_k], 形状和 scores 相同\n",
    "        #-----------------------------------------------------------------         \n",
    "        # 计算上下文向量（也就是注意力的输出）, 是上下文信息的紧凑表示\n",
    "        context = torch.matmul(weights, V) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # context [batch_size, n_heads, len_q, dim_v]\n",
    "        #-----------------------------------------------------------------    \n",
    "        return context, weights # 返回上下文向量和注意力分数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义多头自注意力类\n",
    "d_embedding = 512  # Embedding 的维度\n",
    "n_heads = 8  # Multi-Head Attention 中头的个数\n",
    "batch_size = 3 # 每一批的数据大小\n",
    "class MultiHeadAttention(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(MultiHeadAttention, self).__init__()\n",
    "        self.W_Q = nn.Linear(d_embedding, d_k * n_heads) # Q的线性变换层\n",
    "        self.W_K = nn.Linear(d_embedding, d_k * n_heads) # K的线性变换层\n",
    "        self.W_V = nn.Linear(d_embedding, d_v * n_heads) # V的线性变换层\n",
    "        self.linear = nn.Linear(n_heads * d_v, d_embedding)\n",
    "        self.layer_norm = nn.LayerNorm(d_embedding)\n",
    "    def forward(self, Q, K, V, attn_mask): \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # Q K V [batch_size, len_q/k/v, embedding_dim] \n",
    "        #-----------------------------------------------------------------        \n",
    "        residual, batch_size = Q, Q.size(0) # 保留残差连接\n",
    "        # 将输入进行线性变换和重塑，以便后续处理\n",
    "        q_s = self.W_Q(Q).view(batch_size, -1, n_heads, d_k).transpose(1,2)        \n",
    "        k_s = self.W_K(K).view(batch_size, -1, n_heads, d_k).transpose(1,2)\n",
    "        v_s = self.W_V(V).view(batch_size, -1, n_heads, d_v).transpose(1,2)\n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # q_s k_s v_s: [batch_size, n_heads, len_q/k/v, d_q=k/v]\n",
    "        #----------------------------------------------------------------- \n",
    "        # 将注意力掩码复制到多头 attn_mask: [batch_size, n_heads, len_q, len_k]\n",
    "        attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)\n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # attn_mask [batch_size, n_heads, len_q, len_k]\n",
    "        #----------------------------------------------------------------- \n",
    "        # 使用缩放点积注意力计算上下文和注意力权重\n",
    "        context, weights = ScaledDotProductAttention()(q_s, k_s, v_s, attn_mask)\n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # context [batch_size, n_heads, len_q, dim_v]\n",
    "        # weights [batch_size, n_heads, len_q, len_k]\n",
    "        #----------------------------------------------------------------- \n",
    "        # 通过调整维度将多个头的上下文向量连接在一起\n",
    "        context = context.transpose(1, 2).contiguous().view(batch_size, -1, n_heads * d_v) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # context [batch_size, len_q, n_heads * dim_v]\n",
    "        #-----------------------------------------------------------------        \n",
    "        # 用一个线性层把连接后的多头自注意力结果转换，原始地嵌入维度\n",
    "        output = self.linear(context) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # output [batch_size, len_q, embedding_dim]\n",
    "        #-----------------------------------------------------------------        \n",
    "        # 与输入 (Q) 进行残差链接，并进行层归一化后输出\n",
    "        output = self.layer_norm(output + residual)\n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # output [batch_size, len_q, embedding_dim]\n",
    "        #-----------------------------------------------------------------        \n",
    "        return output, weights # 返回层归一化的输出和注意力权重"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义逐位置前馈网络类\n",
    "class PoswiseFeedForwardNet(nn.Module):\n",
    "    def __init__(self, d_ff=2048):\n",
    "        super(PoswiseFeedForwardNet, self).__init__()\n",
    "        # 定义一维卷积层 1，用于将输入映射到更高维度\n",
    "        self.conv1 = nn.Conv1d(in_channels=d_embedding, out_channels=d_ff, kernel_size=1)\n",
    "        # 定义一维卷积层 2，用于将输入映射回原始维度\n",
    "        self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_embedding, kernel_size=1)\n",
    "        # 定义层归一化\n",
    "        self.layer_norm = nn.LayerNorm(d_embedding)\n",
    "    def forward(self, inputs): \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # inputs [batch_size, len_q, embedding_dim]\n",
    "        #----------------------------------------------------------------                       \n",
    "        residual = inputs  # 保留残差连接 \n",
    "        # 在卷积层 1 后使用 ReLU 激活函数 \n",
    "        output = nn.ReLU()(self.conv1(inputs.transpose(1, 2))) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # output [batch_size, d_ff, len_q]\n",
    "        #----------------------------------------------------------------\n",
    "        # 使用卷积层 2 进行降维 \n",
    "        output = self.conv2(output).transpose(1, 2) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # output [batch_size, len_q, embedding_dim]\n",
    "        #----------------------------------------------------------------\n",
    "        # 与输入进行残差链接，并进行层归一化\n",
    "        output = self.layer_norm(output + residual) \n",
    "        #------------------------- 维度信息 -------------------------------- \n",
    "        # output [batch_size, len_q, embedding_dim]\n",
    "        #----------------------------------------------------------------\n",
    "        return output # 返回加入残差连接后层归一化的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成正弦位置编码表的函数，用于在 Transformer 中引入位置信息\n",
    "def get_sin_enc_table(n_position, embedding_dim):\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # n_position: 输入序列的最大长度\n",
    "    # embedding_dim: 词嵌入向量的维度\n",
    "    #-----------------------------------------------------------------    \n",
    "    # 根据位置和维度信息，初始化正弦位置编码表\n",
    "    sinusoid_table = np.zeros((n_position, embedding_dim))    \n",
    "    # 遍历所有位置和维度，计算角度值\n",
    "    for pos_i in range(n_position):\n",
    "        for hid_j in range(embedding_dim):\n",
    "            angle = pos_i / np.power(10000, 2 * (hid_j // 2) / embedding_dim)\n",
    "            sinusoid_table[pos_i, hid_j] = angle    \n",
    "    # 计算正弦和余弦值\n",
    "    sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2])  # dim 2i 偶数维\n",
    "    sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2])  # dim 2i+1 奇数维    \n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # sinusoid_table 的维度是 [n_position, embedding_dim]\n",
    "    #----------------------------------------------------------------   \n",
    "    return torch.FloatTensor(sinusoid_table)  # 返回正弦位置编码表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义填充注意力掩码函数\n",
    "def get_attn_pad_mask(seq_q, seq_k):\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # seq_q 的维度是 [batch_size, len_q]\n",
    "    # seq_k 的维度是 [batch_size, len_k]\n",
    "    #-----------------------------------------------------------------\n",
    "    batch_size, len_q = seq_q.size()\n",
    "    batch_size, len_k = seq_k.size()\n",
    "    # 生成布尔类型张量\n",
    "    pad_attn_mask = seq_k.data.eq(0).unsqueeze(1)  # <PAD>token 的编码值为 0\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # pad_attn_mask 的维度是 [batch_size，1，len_k]\n",
    "    #-----------------------------------------------------------------\n",
    "    # 变形为与注意力分数相同形状的张量 \n",
    "    pad_attn_mask = pad_attn_mask.expand(batch_size, len_q, len_k)\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # pad_attn_mask 的维度是 [batch_size，len_q，len_k]\n",
    "    #-----------------------------------------------------------------\n",
    "    return pad_attn_mask # 返回填充位置的注意力掩码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义编码器层类\n",
    "class EncoderLayer(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(EncoderLayer, self).__init__()        \n",
    "        self.enc_self_attn = MultiHeadAttention() # 多头自注意力层        \n",
    "        self.pos_ffn = PoswiseFeedForwardNet() # 位置前馈神经网络层\n",
    "    def forward(self, enc_inputs, enc_self_attn_mask):\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_inputs 的维度是 [batch_size, seq_len, embedding_dim]\n",
    "        # enc_self_attn_mask 的维度是 [batch_size, seq_len, seq_len]\n",
    "        #-----------------------------------------------------------------\n",
    "        # 将相同的 Q，K，V 输入多头自注意力层 , 返回的 attn_weights 增加了头数  \n",
    "        enc_outputs, attn_weights = self.enc_self_attn(enc_inputs, enc_inputs,\n",
    "                                               enc_inputs, enc_self_attn_mask)\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_outputs 的维度是 [batch_size, seq_len, embedding_dim] \n",
    "        # attn_weights 的维度是 [batch_size, n_heads, seq_len, seq_len]      \n",
    "        # 将多头自注意力 outputs 输入位置前馈神经网络层\n",
    "        enc_outputs = self.pos_ffn(enc_outputs) # 维度与 enc_inputs 相同\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_outputs 的维度是 [batch_size, seq_len, embedding_dim] \n",
    "        #-----------------------------------------------------------------\n",
    "        return enc_outputs, attn_weights # 返回编码器输出和每层编码器注意力权重"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义编码器类\n",
    "n_layers = 6  # 设置 Encoder 的层数\n",
    "class Encoder(nn.Module):\n",
    "    def __init__(self, corpus):\n",
    "        super(Encoder, self).__init__()        \n",
    "        self.src_emb = nn.Embedding(len(corpus.src_vocab), d_embedding) # 词嵌入层\n",
    "        self.pos_emb = nn.Embedding.from_pretrained( \\\n",
    "          get_sin_enc_table(corpus.src_len+1, d_embedding), freeze=True) # 位置嵌入层\n",
    "        self.layers = nn.ModuleList(EncoderLayer() for _ in range(n_layers))# 编码器层数\n",
    "    def forward(self, enc_inputs):  \n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_inputs 的维度是 [batch_size, source_len]\n",
    "        #-----------------------------------------------------------------\n",
    "        # 创建一个从 1 到 source_len 的位置索引序列\n",
    "        pos_indices = torch.arange(1, enc_inputs.size(1) + 1).unsqueeze(0).to(enc_inputs)\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # pos_indices 的维度是 [1, source_len]\n",
    "        #-----------------------------------------------------------------             \n",
    "        # 对输入进行词嵌入和位置嵌入相加 [batch_size, source_len，embedding_dim]\n",
    "        enc_outputs = self.src_emb(enc_inputs) + self.pos_emb(pos_indices)\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_outputs 的维度是 [batch_size, seq_len, embedding_dim]\n",
    "        #-----------------------------------------------------------------\n",
    "        # 生成自注意力掩码\n",
    "        enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs) \n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_self_attn_mask 的维度是 [batch_size, len_q, len_k]        \n",
    "        #-----------------------------------------------------------------         \n",
    "        enc_self_attn_weights = [] # 初始化 enc_self_attn_weights\n",
    "        # 通过编码器层 [batch_size, seq_len, embedding_dim]\n",
    "        for layer in self.layers: \n",
    "            enc_outputs, enc_self_attn_weight = layer(enc_outputs, enc_self_attn_mask)\n",
    "            enc_self_attn_weights.append(enc_self_attn_weight)\n",
    "        #------------------------- 维度信息 --------------------------------\n",
    "        # enc_outputs 的维度是 [batch_size, seq_len, embedding_dim] 维度与 enc_inputs 相同\n",
    "        # enc_self_attn_weights 是一个列表，每个元素的维度是 [batch_size, n_heads, seq_len, seq_len]          \n",
    "        #-----------------------------------------------------------------\n",
    "        return enc_outputs, enc_self_attn_weights # 返回编码器输出和编码器注意力权重"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成后续注意力掩码的函数，用于在多头自注意力计算中忽略未来信息\n",
    "def get_attn_subsequent_mask(seq):\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # seq 的维度是 [batch_size, seq_len(Q)=seq_len(K)]\n",
    "    #-----------------------------------------------------------------\n",
    "    # 获取输入序列的形状\n",
    "    attn_shape = [seq.size(0), seq.size(1), seq.size(1)]  \n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # attn_shape 是一个一维张量 [batch_size, seq_len(Q), seq_len(K)]\n",
    "    #-----------------------------------------------------------------\n",
    "    # 使用 numpy 创建一个上三角矩阵（triu = triangle upper）\n",
    "    subsequent_mask = np.triu(np.ones(attn_shape), k=1)\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # subsequent_mask 的维度是 [batch_size, seq_len(Q), seq_len(K)]\n",
    "    #-----------------------------------------------------------------\n",
    "    # 将 numpy 数组转换为 PyTorch 张量，并将数据类型设置为 byte（布尔值）\n",
    "    subsequent_mask = torch.from_numpy(subsequent_mask).byte()\n",
    "    #------------------------- 维度信息 --------------------------------\n",
    "    # 返回的 subsequent_mask 的维度是 [batch_size, seq_len(Q), seq_len(K)]\n",
    "    #-----------------------------------------------------------------\n",
    "    return subsequent_mask # 返回后续位置的注意力掩码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义解码器层类\n",
    "class DecoderLayer(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(DecoderLayer, self).__init__()\n",
    "        self.self_attn = MultiHeadAttention()  # 多头自注意力层\n",
    "        self.feed_forward = PoswiseFeedForwardNet()  # 逐位置前馈网络层\n",
    "        self.norm1 = nn.LayerNorm(d_embedding)  # 第一个层归一化\n",
    "        self.norm2 = nn.LayerNorm(d_embedding)  # 第二个层归一化\n",
    "    def forward(self, dec_inputs, attn_mask=None):\n",
    "        # 使用多头自注意力处理输入\n",
    "        attn_output, _ = self.self_attn(dec_inputs, dec_inputs, dec_inputs, attn_mask)\n",
    "        # 将注意力输出与输入相加并进行第一个层归一化\n",
    "        norm1_outputs = self.norm1(dec_inputs + attn_output)\n",
    "        # 将归一化后的输出输入到位置前馈神经网络\n",
    "        ff_outputs = self.feed_forward(norm1_outputs)\n",
    "        # 将前馈神经网络输出与第一次归一化后的输出相加并进行第二个层归一化\n",
    "        dec_outputs = self.norm2(norm1_outputs + ff_outputs)\n",
    "        return dec_outputs # 返回解码器层输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "#  定义解码器类\n",
    "n_layers = 6  # 设置 Decoder 的层数\n",
    "class Decoder(nn.Module):\n",
    "    def __init__(self, vocab_size, max_seq_len):\n",
    "        super(Decoder, self).__init__()\n",
    "        # 词嵌入层（参数为词典维度）\n",
    "        self.src_emb = nn.Embedding(vocab_size, d_embedding)  \n",
    "        # 位置编码层（参数为序列长度）\n",
    "        self.pos_emb = nn.Embedding(max_seq_len, d_embedding)\n",
    "        # 初始化 N 个解码器层       \n",
    "        self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)]) \n",
    "    def forward(self, dec_inputs):        \n",
    "        # 创建位置信息\n",
    "        positions = torch.arange(len(dec_inputs), device=dec_inputs.device).unsqueeze(-1)\n",
    "        # 将词嵌入与位置编码相加\n",
    "        inputs_embedding = self.src_emb(dec_inputs) + self.pos_emb(positions)\n",
    "        # 生成自注意力掩码\n",
    "        attn_mask = get_attn_subsequent_mask(inputs_embedding).to(device)\n",
    "        # 初始化解码器输入，这是第一层解码器层的输入 \n",
    "        dec_outputs =  inputs_embedding \n",
    "        for layer in self.layers:\n",
    "            # 将输入数据传递给解码器层，并返回解码器层的输出，作为下一层的输入\n",
    "            dec_outputs = layer(dec_outputs, attn_mask) \n",
    "        return dec_outputs # 返回解码器输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义 GPT 模型\n",
    "class GPT(nn.Module):\n",
    "    def __init__(self, vocab_size, max_seq_len):\n",
    "        super(GPT, self).__init__()\n",
    "        self.decoder = Decoder(vocab_size, max_seq_len) # 解码器，用于学习文本生成能力\n",
    "        self.projection = nn.Linear(d_embedding, vocab_size)  # 全连接层，输出预测结果\n",
    "    def forward(self, dec_inputs):        \n",
    "        dec_outputs = self.decoder(dec_inputs) # 将输入数据传递给解码器\n",
    "        logits = self.projection(dec_outputs) # 传递给全连接层以生成预测\n",
    "        return logits # 返回预测结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构建语料库\n",
    "from collections import Counter\n",
    "class LanguageCorpus:\n",
    "    def __init__(self, sentences):\n",
    "        self.sentences = sentences\n",
    "        # 计算语言的最大句子长度，并加 2 以容纳特殊符号 <sos> 和 <eos>\n",
    "        self.seq_len = max([len(sentence.split()) for sentence in sentences]) + 2\n",
    "        self.vocab = self.create_vocabulary() # 创建源语言和目标语言的词汇表\n",
    "        self.idx2word = {v: k for k, v in self.vocab.items()} # 创建索引到单词的映射\n",
    "    def create_vocabulary(self):\n",
    "        vocab = {'<pad>': 0, '<sos>': 1, '<eos>': 2}\n",
    "        counter = Counter()\n",
    "        # 统计语料库的单词频率\n",
    "        for sentence in self.sentences:\n",
    "            words = sentence.split()\n",
    "            counter.update(words)\n",
    "        # 创建词汇表，并为每个单词分配一个唯一的索引\n",
    "        for word in counter:\n",
    "            if word not in vocab:\n",
    "                vocab[word] = len(vocab)\n",
    "        return vocab\n",
    "    def make_batch(self, batch_size, test_batch=False):\n",
    "        input_batch, output_batch = [], [] # 初始化批数据\n",
    "        sentence_indices = torch.randperm(len(self.sentences))[:batch_size] # 随机选择句子索引\n",
    "        for index in sentence_indices:\n",
    "            sentence = self.sentences[index]\n",
    "            # 将句子转换为索引序列\n",
    "            seq = [self.vocab['<sos>']] + [self.vocab[word] for word in sentence.split()] + [self.vocab['<eos>']]\n",
    "            seq += [self.vocab['<pad>']] * (self.seq_len - len(seq)) # 对序列进行填充\n",
    "            # 将处理好的序列添加到批次中\n",
    "            input_batch.append(seq[:-1])\n",
    "            output_batch.append(seq[1:])\n",
    "        return torch.LongTensor(input_batch), torch.LongTensor(output_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 语料库词汇表大小 : 15\n",
      " 最长句子长度 : 7\n"
     ]
    }
   ],
   "source": [
    "#处理语言模型数据集\n",
    "with open(\"text.txt\", \"r\") as file: # 从文件中读入语料\n",
    "    sentences = [line.strip() for line in file.readlines()]\n",
    "corpus = LanguageCorpus(sentences) # 创建语料库\n",
    "vocab_size = len(corpus.vocab) # 词汇表大小\n",
    "max_seq_len = corpus.seq_len # 最大句子长度（用于设置位置编码）\n",
    "print(f\" 语料库词汇表大小 : {vocab_size}\") # 打印词汇表大小\n",
    "print(f\" 最长句子长度 : {max_seq_len}\") # 打印最大序列长"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型的参数量为: 18945551\n"
     ]
    }
   ],
   "source": [
    "\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # 设置设备\n",
    "model = GPT(vocab_size, max_seq_len).to(device) # 创建 GPT 模型实例\n",
    "criterion = nn.CrossEntropyLoss() # 损失函数\n",
    "optimizer = optim.Adam(model.parameters(), lr=0.0001) # 优化器\n",
    "# 计算模型参数量的函数，修正了拼写错误\n",
    "def count_parameters(model):\n",
    "    return sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
    "# 获取模型参数量\n",
    "param_count = count_parameters(model)\n",
    "print(f\"模型的参数量为: {param_count}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "#训练模型\n",
    "\n",
    "epochs = 50 # 训练轮次\n",
    "for epoch in range(epochs):  # 训练 epochs 轮\n",
    "    optimizer.zero_grad() # 梯度清零\n",
    "    inputs, targets = corpus.make_batch(batch_size) # 创建训练数据\n",
    "    inputs, targets = inputs.to(device), targets.to(device)\n",
    "    #print(inputs, targets)\n",
    "    outputs = model(inputs) # 获取模型输出 \n",
    "    loss = criterion(outputs.view(-1, vocab_size), targets.view(-1)) # 计算损失\n",
    "    if (epoch + 1) % 100 == 0: # 打印损失\n",
    "        print(f\"Epoch: {epoch + 1:04d} cost = {loss:.6f}\")\n",
    "    loss.backward() # 反向传播\n",
    "    optimizer.step() # 更新参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 生成的文本 : masked_fill_ 函数的 attn_mask 是布尔类型的数据，并且其内容能够准确反映出你期望的掩码情况。\n"
     ]
    }
   ],
   "source": [
    "# 测试文本生成\n",
    "def generate_text(model, input_str, max_len=50):\n",
    "    model.eval()  # 将模型设置为评估（测试）模式，关闭 dropout 和 batch normalization 等训练相关的层\n",
    "    # 将输入字符串中的每个 token 转换为其在词汇表中的索引\n",
    "    input_tokens = [corpus.vocab[token] for token in input_str]\n",
    "    # 创建一个新列表，将输入的 tokens 复制到输出 tokens 中 , 目前只有输入的词\n",
    "    output_tokens = input_tokens.copy()\n",
    "    with torch.no_grad():  # 禁用梯度计算，以节省内存并加速测试过程\n",
    "        for _ in range(max_len):  # 生成最多 max_len 个 tokens\n",
    "            # 将输出的 token 转换为 PyTorch 张量，并增加一个代表批次的维度 [1, len(output_tokens)]\n",
    "            inputs = torch.LongTensor(output_tokens).unsqueeze(0).to(device)\n",
    "            outputs = model(inputs) # 输出 logits 形状为 [1, len(output_tokens), vocab_size]\n",
    "            # 在最后一个维度上获取 logits 中的最大值，并返回其索引（即下一个 token）\n",
    "            _, next_token = torch.max(outputs[:, -1, :], dim=-1)            \n",
    "            next_token = next_token.item() # 将张量转换为 Python 整数            \n",
    "            if next_token == corpus.vocab[\"<eos>\"]:\n",
    "                break # 如果生成的 token 是 EOS（结束符），则停止生成过程           \n",
    "            output_tokens.append(next_token) # 将生成的 tokens 添加到 output_tokens 列表\n",
    "    # 将输出 tokens 转换回文本字符串\n",
    "    output_str = \" \".join([corpus.idx2word[token] for token in output_tokens])\n",
    "    return output_str\n",
    "input_str = [\"masked_fill_\"] # 输入一个词：Python\n",
    "generated_text = generate_text(model, input_str) # 模型跟着这个词生成后续文本\n",
    "print(\" 生成的文本 :\", generated_text) # 打印预测文本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
